<template>
  <div>
  <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="120px" :disabled="disabled">
    <el-row>
      <el-col :span="12">
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="formData.ruleName" clearable placeholder="请输入规则名称" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="消息模板" prop="tempId">
          <el-select v-model="formData.tempId" placeholder="请选择" clearable>
            <el-option v-for="item in templateList" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="地震类型" prop="earthquakeType">
          <el-radio-group v-model="formData.earthquakeType">
            <el-radio value="1">正式</el-radio>
            <el-radio value="2">测试</el-radio>
            <el-radio value="3">演练</el-radio>
            <el-radio value="4">自动</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="应急响应级别">
          <el-row :gutter="5" style="width: 100%;">
            <el-col :span="7">
              <el-input v-model.number="formData.responseLevel1" style="width:100%" clearable onkeyup="value=value.replace(/[^\d]+/g,'')"/>
            </el-col>
            <el-col :span="4">
              <el-select v-model="formData.responseLevel2" clearable>
                <el-option v-for="item in symbolOption" :label="item.label" :value="item.value" />
              </el-select>
            </el-col>
            <el-col :span="2" style="text-align: center">
              级别
            </el-col>
            <el-col :span="4">
              <el-select v-model="formData.responseLevel3" clearable>
                <el-option v-for="item in symbol1Option" :label="item.label" :value="item.value" />
              </el-select>
            </el-col>
            <el-col :span="7" style="position: relative;">
              <el-input v-model.number="formData.responseLevel4" style="width:100%" clearable onkeyup="value=value.replace(/[^\d]+/g,'')"/>
            </el-col>
          </el-row>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="是否台湾区域" prop="isTw">
          <el-select v-model="formData.isTw" placeholder="请选择" clearable>
            <el-option v-for="item in isOption" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="震级范围">
          <el-row :gutter="5" style="width: 100%;">
            <el-col :span="7">
              <el-input-number v-model="formData.magnitude1" :precision="1" :step="1" controls-position="right"
                style="width:100%" clearable />
            </el-col>
            <el-col :span="4">
              <el-select v-model="formData.magnitude2" clearable>
                <el-option v-for="item in symbolOption" :label="item.label" :value="item.value" />
              </el-select>
            </el-col>
            <el-col :span="2" style="text-align: center">
              震级
            </el-col>
            <el-col :span="4">
              <el-select v-model="formData.magnitude3" clearable>
                <el-option v-for="item in symbol1Option" :label="item.label" :value="item.value" />
              </el-select>
            </el-col>
            <el-col :span="7" style="position: relative;">
              <el-input-number v-model="formData.magnitude4" :precision="1" :step="1" controls-position="right"
                style="width:100%" clearable />
            </el-col>
          </el-row>
        </el-form-item>
      </el-col>
      <el-col>
        <el-form-item label="区域范围:" prop="rangeType" style="position: relative;">
          <el-radio-group v-model="formData.rangeType" class="!w-300px" :disabled="disabled" @change="changeRadio">
            <el-radio value="0" >上传区域文件</el-radio>
            <el-radio value="1" @click="clickRadio">按行政区划选择</el-radio>
          </el-radio-group>
          <ProvinceCity ref="provinceRef" :regionLists="formData.regionList" @querySelect="querySelect"></ProvinceCity>
        </el-form-item>

        <el-form-item label=" " prop="fileIds" v-if="formData.rangeType == '0'" style="width:100%">
          <UploadFile v-model="formData.list" @uploadSuccess="uploadSuccess" :disabled="disabled"
            :limit=1></UploadFile>
        </el-form-item>
        <el-form-item v-if="formData.rangeType == '1'" label=" ">
          {{ regionLists }}
        </el-form-item>
        <el-form-item label=" " >
            <el-col :span="12" style="height: 400px;">
               <LoadMap :fileidInfo="fileidInfo" style="height: 100%" />
              <!-- <div id="map" ref="mapElement" style="width:100%;height:100%" v-show="formData.rangeType == '0'"></div> -->
          </el-col>
          </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="接收用户组" prop="userGroups">
          <el-select v-model="formData.userGroups" multiple placeholder="请选择" clearable>
            <el-option v-for="item in groupList" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <div style="text-align: center;">
      <el-button :disabled="formLoading" type="primary" @click="submitForm" v-if="formType != '查看'">确 定</el-button>
      <el-button @click="setClose">取 消</el-button>
  </div>
  </div>
</template>
<script lang="ts" setup>
import * as publishRuleApi from '@/api/infoArrive/arriveNotice/publishRule'
import { getGroup, formDataOv } from '@/api/infoArrive/arriveNotice/userGroup'
import { getTemplateList } from '@/api/infoArrive/arriveNotice/messageTemplate/index'
import UploadFile from '@/views/responseLevel/populationDensity/create/UploadFile.vue'
import ProvinceCity from '@/views/responseLevel/populationDensity/create/provinceCity.vue'

import LoadMap from '@/views/earthquake/earthquakeServer/gis/LoadMap.vue'
defineOptions({ name: 'PublishRuleForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const disabled = ref(false)
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<any>({
  ruleName: '',
  resLevelName: '',
  earthquakeType: '',//地震类型  1--正式地震  2--测试地震  3--演练地震  4--自动地震, 手动触发默认是2 测试地震
  isTw: '0',
  tempId: '',
  userGroups: [],
  magnitude1: undefined,
  magnitude2: 0,
  magnitude3: 0,
  magnitude4: undefined,
  responseLevel1: undefined,
  responseLevel2: 0,
  responseLevel3: 0,
  responseLevel4: undefined,
  rangeType: "0",
  list: [],
  fileIds: '',
  regionList: [],
})
const regionLists = ref('')
const symbol1Option = ref([
  { label: '≤', value: 0 }, { label: '<', value: 1 }, { label: '=', value: 2 },
])
const symbolOption = ref([
  { label: '≤', value: 0 }, { label: '<', value: 1 },
])
const isOption = ref([
  { label: '否', value: '0' }, { label: '是', value: '1' }
])

const formRules = reactive({
  ruleName: [{ required: true, message: '规则名称不能为空', trigger: 'blur' }],
  earthquakeType: [{ required: true, message: '地震类型不能为空', trigger: 'blur' }],
  tempId: [{ required: true, message: '请选择', trigger: 'change' }],
  userGroups: [{ required: true, message: '请选择', trigger: 'change' }],
  isTw: [{ required: true, message: '请选择', trigger: 'change' }],
  rangeType: [{ required: true, message: '请选择', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref

//初始化 type 0 -- 临时表 1 ---正式表 owner public公库 private四库
const fileidInfo = ref({
  fileid: '',
  type: 0,
  xzqh:[],
  query: {
    tableName: '',
    fields: '',
    // owner:"private"
  }
})

/** 打开弹窗 */
const open = async (type: string, id?: number) => {

 if (type == '修改' || type == '查看') {
    fileidInfo.value.type = 1
    fileidInfo.value.fileid = id
    fileidInfo.value.query.tableName = 'pn_region_common'
    fileidInfo.value.query.fields = 'id,rule_id,province,city,del_flag,create_user,update_user,update_user,create_time'
    fileidInfo.value.query.filter = `rule_id='${id}'`
  } else {
    fileidInfo.value.type = 0
    fileidInfo.value.fileid = ''
    fileidInfo.value.query.tableName = 'temp_file_data'
    fileidInfo.value.query.fields = 'id'
  }

  dialogVisible.value = true
  dialogTitle.value = type
  disabled.value = (type === '查看')
  formType.value = type
  resetForm()
  await getGroupList()
  await getTemplateLists()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await publishRuleApi.getPublishRule(id)
      formData.value.userGroups = formData.value.userGroups.split(',')
      formData.value.list.forEach(item=>{
        item.name = item.attachName;
        item.url = item.attachId;
      })
      if (formData.value.regionList.length>0) {
      let data = []
      formData.value.regionList.forEach(item=>{
        if (item.city !== 'undefined' || !item.city) data.push(item.province)
        else data.push(item.province + '-' + item.city)
      })
      regionLists.value = data.join(',')
      } else {
        formData.value.regionList = []
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success', 'setClose']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    if (formData.value.rangeType == "0") {
      if (formData.value.list.length == 0) {
        message.warning('请上传shp数据')
        return
      }
      formData.value.fileIds = formData.value.list.map(item => item.url).join(',');
    } else {
      if (formData.value.regionList.length == 0) {
        message.warning('请选择行政区划')
        return
      }
    }
    if (formType.value === '新增') {
      await publishRuleApi.savePublishRule({ ...formData.value, userGroups: formData.value.userGroups.join(',') })
      message.success(t('common.createSuccess'))
    } else {
      await publishRuleApi.savePublishRule({ ...formData.value, userGroups: formData.value.userGroups.join(',') })
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
    setClose()
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    ruleName: '',
    resLevelName: '',
    earthquakeType: '',
    isTw: '0',
    tempId: '',
    userGroups: [],
    magnitude1: undefined,
    magnitude2: 0,
    magnitude3: 0,
    magnitude4: undefined,
    responseLevel1: undefined,
    responseLevel2: 0,
    responseLevel3: 0,
    responseLevel4: undefined,
    rangeType: '0',
    list: [],
    fileIds: '',
    regionList: [],
  }
  formRef.value?.resetFields()
}

/** 获取信息模板的数据  */
const templateList = ref([] as any[])
const getTemplateLists = async () => {
  const { list } = await getTemplateList({ pageNo: 1, pageSize: 2000 })
  list.forEach(item => {
    item.label = item.templateName;
    item.value = item.id;
  })
  templateList.value = list
}
/** 获取用户组的数据  */
const groupList = ref([] as any[])
const getGroupList = async () => {
  const res = await getGroup({ groupType: '1' })
  res.list.forEach(item => {
    item.label = item.groupName;
    item.value = item.id;
  })
  groupList.value = res.list
}
const setClose = () => {
  dialogVisible.value = false
  emit('setClose')
}
const provinceRef = ref()
const querySelect=(value)=>{
  let data:any=[];
  value.forEach(item=>{
    if(item.city){
      data.push(item.province + '-' + item.city)
    }else{
      data.push(item.province)
    }
  })
  regionLists.value=data.join(',');
  formData.value.regionList = value;


  var cityArr: any = [];

  value.forEach((item) => {
    if (item.city) {
      cityArr.push({
        code:item.code,
        name:item.city,
        type:3
      });
    } else {
      if(item.province == "全国"){
         cityArr.push({
        code:"",
        name:item.province,
        type:1
      });
      return
      }
      if(item.code){
      cityArr.push({
              code:item.code,
              name:item.province,
              type:2
            });
      }
       
    }
  })
    fileidInfo.value.type = 2;
     fileidInfo.value.fileid = Date.now() +"";
    fileidInfo.value.xzqh = cityArr;
}
const uploadSuccess = (value) => {
  formData.value.list = value;
  
   fileidInfo.value.type = 0
    fileidInfo.value.query.tableName = 'temp_file_data'
    fileidInfo.value.query.fields = 'id'
     fileidInfo.value.query.filter = `id='${value[0].id}'`
  fileidInfo.value.fileid = value[0].id
}
const clickRadio = () => {
  if(formData.value.type==0&&disabled.value) return;
  provinceRef.value.open()
}
const changeRadio = (value)=>{
  if(value==0){
      provinceRef.value?.close()
    }else if(value==1){
      provinceRef.value.open()
    }
}

</script>
